<?php
namespace util;

use app\admin\model\LogErrorModel;
use think\facade\Log;
use think\facade\Request;

class Logger
{
    public static function getErrorDesc(\Throwable $exception) {
        if(empty($exception)) return '';
        return "FILE:" . $exception->getFile() . " LINE:" . $exception->getLine() . " MESSAGE:" . $exception->getMessage();
    }

    /**
     * 添加错误日志
     * @param $msg
     * @param string $businessCode
     * @param $exception
     */
    public static function error($exception, $msg, $level = 'error', $businessCode = 'default') {
        try {
            $str = '';
            $trace = "";
            if($exception != null) {
                $str = "MESSAGE:" . $exception->getMessage() . " FILE:" . $exception->getFile() . " LINE:" . $exception->getLine();
                $trace = $exception->getTraceAsString();
                $msg = $msg .'【'. $exception->getCode() .'】' . ' '. $str; 
            }
            $params = array_merge(input('get.'), input('post.'));
            (new LogErrorModel())->create([
                'level' => $level,
                'business_code' => $businessCode,
                'meta' => self::getRequiredInfo(),
                'message' => $msg,
                'trace' => $trace,
                'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
                'create_time' => date('Y-m-d H:i:s', time())
            ]);
            // Log::write($msg, 'error');
        } catch (\Throwable $th) {
            exit(var_dump($th));
            // var_dump($th);
        }
    }

    private static function getRequiredInfo() {
        $request = Request::instance();
        $url = $request->url(true);
        $method = $request->method();
        $ip = $request->ip();
        return "$ip $method $url";
    }

    public static function info($msg) {
        try {
            Log::write($msg, 'info');
        } catch (\Throwable $th) {
        }
    }

    public static function record($msg, $type = 'log') {
        Log::record($msg, $type);
    }
}
